<?php

namespace app\admin\model;

use think\Model;
use app\admin\model\Admin as AdminModel;

class AuthGroup extends Model {

    function groupTree() {
        // 所有管理组数据
        $groups = $this->order('id desc')->select();
        return $this->sort($groups);
    }

    function sort($data, $pid = 0) {
        static $sortArr = array();
        foreach ($data as $k => $v) {

            if ($pid == $v['pid']) {

                $sortArr[] = $v;

                // 递归添加到数组中
                $this->sort($data, $v['id']);

            }

        }
        return $sortArr;
    }

    /**
     * 根据当前的用户组id去删除当前用户组下所有用户
     */
    function delSameGroupUsers($group_id) {

        // 当前用户组下所有用户的id
        $sameGroupUserIDs = db('auth_group_access')
            ->where('group_id', $group_id)
            ->column('uid');

        // 删除所有的同组用户
        foreach ($sameGroupUserIDs as $key => $value) {
            AdminModel::destroy($value);
        }

    }

    /**
     * 递归获取当前用户组的子用户组
     */
    function recursiveGetSonIDs($pid){

        static $arr = array();

        $sonGroupIDs = self::where('pid', $pid)->column('id');
        if ($sonGroupIDs !== null) { // 有子用户组
            foreach ($sonGroupIDs as $key => $value) {
                $arr[] = $value;
                $this->recursiveGetSonIDs($value);
            }
        }

        return $arr;

    }

    /**
     * 拿到当前用户组对应的所有规则
     */
    function getRules($id) {

        $extendsRules = self::where('id', $id)->value('rules');

        return $extendsRules;

    }

}
